﻿using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.FormService;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DevSamPle.FormPlugin
{
    [Description("【表单插件】BeforeSave获取销售订单合并的行号"), HotUpdate]
    public class CustBeforeSave : AbstractBillPlugIn
    {
        public override void BeforeSave(BeforeSaveEventArgs e)
        {
            base.BeforeSave(e);
            var obj = this.Model.DataObject;
            int salSeq = Convert.ToInt32(obj["SaleOrderEntrySeq"]);
            if (salSeq == 0)
            {
                string salNo = Convert.ToString(obj["SaleOrderNo"]);
                DynamicObject material = obj["MaterialId"] as DynamicObject;
                int matId = material == null ? 0 : Convert.ToInt32(material["Id"]);
                int seq = GetSalSeq(matId, salNo);
                this.Model.SetValue("FSaleOrderEntrySeq", seq, 0);
            }
        }

        private int GetSalSeq(int matId, string salNo)
        {
            int salSeq = 0;
            var result = WebApiServiceCall.ExecuteBillQuery(this.Context, QueryParameter("SAL_SaleOrder", "FSaleOrderEntry_FSeq", $"fbillno='{salNo}' and FMaterialId={matId}"));
            if (result.Count > 0)
            {
                salSeq = Convert.ToInt32(result.FirstOrDefault().FirstOrDefault());
            }
            return salSeq;
        }
        private string QueryParameter(string formId, string fieldKeys, string filterString)
        {
            var param = new
            {
                FormId = formId,
                FieldKeys = fieldKeys,
                FilterString = filterString
            };
            return JsonConvert.SerializeObject(param);
        }
    }
}
